<template>
  <div>
    <el-breadcrumb class="breadcrumb-container" separator=">">
      <el-breadcrumb-item :to="{ path: '/bidder/inquiries' }">询标列表</el-breadcrumb-item>
      <el-breadcrumb-item>询标详情</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 询标信息卡片 -->
    <el-card class="inquiry-card">
      <div slot="header" class="card-header">
        <div class="header-left">
          <i class="el-icon-document" style="color: #409eff; margin-right: 8px;"></i>
          <span class="card-title">询标信息</span>
        </div>
        <el-tag v-if="countdownVisible" type="primary" effect="plain" class="countdown-tag">
          <i class="el-icon-time" style="margin-right: 4px;"></i>
          {{ countdownText }}
        </el-tag>
      </div>
      <div class="card-content">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <div class="info-label">
                <i class="el-icon-postcard" style="color: #409eff; margin-right: 8px;"></i>
                项目编号
              </div>
              <div class="info-value">{{projectNo}}</div>
            </div>
          </el-col>
          <!-- <el-col :span="12">
            <div class="info-item">
              <div class="info-label">
                <i class="el-icon-edit-outline" style="color: #409eff; margin-right: 8px;"></i>
                询标内容
              </div>
              <div class="info-value">
               {{inquiryContent}}
              </div>
            </div>
          </el-col> -->
          <el-col :span="24">
            <div class="info-item">
              <div class="info-label">
                <i class="el-icon-paperclip" style="color: #409eff; margin-right: 8px;"></i>
                附件内容
              </div>
              <div class="attachment-content">
                <div v-if="attachmentList.length > 0" class="attachment-list">
                  <el-tag
                    v-for="file in attachmentList"
                    :key="file.Id"
                    type="primary"
                    effect="plain"
                    class="attachment-tag"
                    @click="downloadFile(file)"
                  >
                    <i :class="getFileIcon(file.DisplayName)" style="margin-right: 4px;"></i>
                    {{ file.DisplayName }}
                    <i class="el-icon-download" style="margin-left: 4px;"></i>
                  </el-tag>
                </div>
                <div v-else class="no-attachment">
                  暂无附件
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 回复表单卡片 -->
    <el-card class="reply-card">
      <div slot="header" class="card-header">
        <div class="header-left">
          <i class="el-icon-chat-line-round" style="color: #409eff; margin-right: 8px;"></i>
          <span class="card-title">询标回复</span>
        </div>
      </div>
      <div class="card-content">
        <el-form ref="form" :model="formData">
          <el-row>
            <!-- <el-col :span="24">
              <el-form-item label="回复内容" prop="ReplyContent" :rules="[{ required: true, message: '请输入回复内容', trigger: 'blur' }]">
                <el-input
                  v-model="formData.ReplyContent"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入回复内容"
                  maxlength="1000"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-col> -->
             <el-col :span="24">
                <UploadFile title="回复附件" :files="formData.Attachement" />
              </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="card-actions">
        <el-button
          type="primary"
          :loading="submitting"
          @click="submitReply"
        >
          <i class="el-icon-s-promotion" style="margin-right: 4px;"></i>
          提交回复
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { GetInquiryRecordById, GetInquiryReplyRecordById } from "@/api/InquiryRecord";
import { AddInquiryReplyRecord } from "@/api/InquiryRecord";
import UploadFile from '@/components/UploadFile.vue';
import router from '@/router';
import { Message } from 'element-ui'

export default {
  name: 'BidderHome',
  components: {
    UploadFile
  },
  setup() {
    const { ref, computed, onMounted, onBeforeUnmount } = require('vue');
    const route = router.currentRoute;

    // 添加响应式变量
    const inquiryId = ref('');
    const projectNo = ref('');
    const unitId = ref('');
    const unitName = ref('');
    const inquiryContent = ref('');
    const attachmentList = ref([]); // 用于存储询标附件列表

    // 表单相关
    const form = ref(null);
    const valid = ref(false);
    const replyContent = ref("");
    const attachments = ref([]);
    const submitting = ref(false);
    const inquiryReplyRecord = ref(null);

    // 倒计时相关
    const deadline = ref(null);
    const countdownText = ref('');
    const countdownVisible = ref(false);
    let countdownTimer = null;

    // 后端参数
    const formData = ref({
      ReplyContent: "",
      Attachement: [],
    });

    // 倒计时函数
    const pad = (n) => String(n).padStart(2, '0');
    const parseDeadline = (val) => {
      if (!val) return null;
      let t = Date.parse(val);
      if (!isNaN(t)) return t;
      t = Date.parse(String(val).replace(/-/g, '/')); // 兼容 yyyy-MM-dd HH:mm:ss
      return isNaN(t) ? null : t;
    };
    const updateCountdown = () => {
      const end = parseDeadline(deadline.value);
      if (!end) {
        countdownVisible.value = false;
        return;
      }
      const diff = end - Date.now();
      if (diff <= 0) {
        countdownVisible.value = false;
        if (countdownTimer) {
          clearInterval(countdownTimer);
          countdownTimer = null;
        }
        return;
      }
      const totalSec = Math.floor(diff / 1000);
      const hours = Math.floor(totalSec / 3600);
      const minutes = Math.floor((totalSec % 3600) / 60);
      const seconds = totalSec % 60;
      countdownText.value = `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
      countdownVisible.value = true;
    };

    onMounted(async () => {
      inquiryId.value = route.query.Id || '';
      projectNo.value = route.query.projectNo || '';
      unitId.value = route.query.unitId || '';
      unitName.value = route.query.unitName || '';
      console.log('获取到的参数:', {
        inquiryId: inquiryId.value,
        projectNo: projectNo.value
      });

      if (inquiryId.value) {
        const inquiryReply = await GetInquiryReplyRecordById(inquiryId.value);
        console.log('获取到的询标回复ID:', inquiryReply.Data.InquiryRecordId);
        const inquiry = await GetInquiryRecordById(inquiryReply.Data.InquiryRecordId);
        inquiryReplyRecord.value = inquiryReply.Data;
        inquiryContent.value = inquiry.Data.InquiryContent;
        projectNo.value = inquiry.Data.ProjectNo;
        attachmentList.value = inquiry.Data.Attachement || [];

        // 启用倒计时（采用询标回复中的 DeadlineTime）
        deadline.value = inquiryReplyRecord.value && inquiryReplyRecord.value.DeadlineTime;
        updateCountdown();
        if (!countdownTimer) {
          countdownTimer = setInterval(updateCountdown, 1000);
        }
      }
    });

    onBeforeUnmount(() => {
      if (countdownTimer) {
        clearInterval(countdownTimer);
        countdownTimer = null;
      }
    });

    const getFileIcon = (filename) => {
      const ext = filename.split('.').pop().toLowerCase();
      switch (ext) {
        case 'pdf':
          return 'el-icon-document';
        case 'doc':
        case 'docx':
          return 'el-icon-document';
        case 'xls':
        case 'xlsx':
          return 'el-icon-s-grid';
        case 'jpg':
        case 'jpeg':
        case 'png':
          return 'el-icon-picture';
        default:
          return 'el-icon-document';
      }
    };

    const downloadFile = async (file) => {
      try {
        const link = document.createElement('a');
        link.href = file.FileAllPath;
        link.target = '_blank';
        link.download = file.DisplayName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        console.error('下载文件失败:', error);
        Message.error('下载文件失败，请稍后重试');
      }
    };

    // 提交回复
    const submitReply = async () => {
      if (!form.value.validate()) return;
      submitting.value = true;
      try {
        inquiryReplyRecord.value.ReplyContent = formData.value.ReplyContent;
        inquiryReplyRecord.value.Attachement = formData.value.Attachement;
        const res = await AddInquiryReplyRecord(inquiryReplyRecord.value);
        if (res.IsSuccess === true) {
          Message.success("回复提交成功");
          router.push({
            path: '/bidder/inquiries',
            query: {
              unitId: unitId.value,
              unitName: unitName.value,
              timestamp: new Date().getTime()
            }
          });
        } else {
          Message.error("回复提交失败，请稍后重试");
        }
      } catch (error) {
        Message.error("回复提交失败");
      } finally {
        submitting.value = false;
      }
    };

    const goBack = () => {
      router.back();
    };

    return {
      inquiryId,
      projectNo,
      unitId,
      unitName,
      inquiryContent,
      attachmentList,
      form,
      valid,
      replyContent,
      attachments,
      submitting,
      inquiryReplyRecord,
      formData,
      getFileIcon,
      downloadFile,
      submitReply,
      goBack,
      countdownText,
      countdownVisible,
    };
  }
};
</script>

<style scoped>
.breadcrumb-container {
  margin-bottom: 20px;
}

.inquiry-card,
.reply-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.inquiry-card:hover,
.reply-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.header-left {
  display: flex;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.countdown-tag {
  font-size: 12px;
}

.card-content {
  padding: 20px 0;
}

.info-item {
  padding: 16px;
  border-radius: 12px;
  background-color: rgba(64, 158, 255, 0.05);
  transition: all 0.3s ease;
  border: 1px solid rgba(64, 158, 255, 0.1);
  margin-bottom: 16px;
}

.info-item:hover {
  background-color: rgba(64, 158, 255, 0.08);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.info-label {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.info-value {
  color: #303133;
  line-height: 1.6;
  font-weight: 500;
  padding: 4px 0;
}

.attachment-content {
  margin-top: 8px;
}

.attachment-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.attachment-tag {
  cursor: pointer;
  transition: all 0.3s ease;
  margin-right: 8px;
  margin-bottom: 8px;
}

.attachment-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.no-attachment {
  color: #909399;
  font-size: 14px;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  padding: 16px 0 0 0;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .card-content {
    padding: 16px 0;
  }
  
  .info-item {
    padding: 12px;
  }
  
  .attachment-list {
    justify-content: center;
  }
}

@media (max-width: 600px) {
  .card-title {
    font-size: 16px;
  }
  
  .info-label {
    font-size: 12px;
  }
  
  .info-value {
    font-size: 14px;
  }
  
  .attachment-tag {
    font-size: 12px;
  }
}
</style>
